'use strict';
const Service = require('egg').Service;

class userInfoService extends Service {
  async login(params) {
    const ctx = this.ctx;
    const { phoneNo, password } = params;
    const model = await ctx.model.User.findOne({
      attributes: { exclude: [ 'password' ] },
      where: {
        phoneNo,
        password,
      },
    });
    if (model) {
      ctx.session.sessionInfo = model.toJSON();
      await this.addLoginHistory({
        operationType: 1,
        phoneNo,
      });
    }
    return await ctx.service.returnBody.index(model, '用户名密码错误！');
  }
  async register(params) {
    const ctx = this.ctx;
    const { phoneNo, password, phoneCode, nickName, protocolTime } = params;
    const tempPhoneCode = ctx.session.phoneCode;
    if (!tempPhoneCode || tempPhoneCode !== phoneCode) {
      return await ctx.service.returnBody.index(null, '请先获取验证码！');
    }
    const model = await ctx.model.User.findOne({
      raw: true,
      attributes: [ 'id' ],
      where: {
        [ctx.app.Sequelize.Op.or]: [{ phoneNo }, { nickName }],
      },
    });
    if (model) {
      return await ctx.service.returnBody.index(null, '手机号或昵称已存在！');
    }
    if (tempPhoneCode === phoneCode) {
      const now = new Date();
      const params = {
        phoneNo,
        password,
        nickName,
        createdTime: now,
        updatedTime: now,
        protocolTime,
      };
      const model = await ctx.model.User.create(params);
      if (model) {
        ctx.session.phoneCode = null;
        return await ctx.service.returnBody.index({});
      }
    }
    return await ctx.service.returnBody.index(null, '注册失败！');
  }
  async verificationCode(params) {
    const ctx = this.ctx;
    const { phoneNo } = params;
    const phoneCode = Math.random().toString().slice(-6);
    const ossUrl = ctx.app.config.ossUrl;
    const result = await ctx.curl(ossUrl.sendVerify, {
      method: 'POST',
      contentType: 'json',
      data: {
        phone_number: [ phoneNo ],
        param: [{
          code: phoneCode,
        }],
      },
      dataType: 'json',
    });
    if (result && result.data && result.data.code === 200) {
      ctx.session.phoneCode = phoneCode;
      return await ctx.service.returnBody.index({});
    }
    return await ctx.service.returnBody.index(null, '获取验证码失败！');
  }
  async retrievePassword(params) {
    const ctx = this.ctx;
    const { phoneNo, password, phoneCode } = params;
    const tempPhoneCode = ctx.session.phoneCode;
    if (!tempPhoneCode || tempPhoneCode !== phoneCode) {
      return await ctx.service.returnBody.index(null, '请先获取验证码！');
    }
    if (tempPhoneCode === phoneCode) {
      const now = new Date();
      const model = await ctx.model.User.update({
        phoneNo,
        password,
        updatedTime: now,
      }, {
        where: {
          phoneNo,
        },
      });
      if (model) {
        ctx.session.phoneCode = null;
        return await ctx.service.returnBody.index({});
      }
    }
    return await ctx.service.returnBody.index(null, '找回密码失败！');
  }
  async logout(params) {
    const ctx = this.ctx;
    const { phoneNo, type } = params;
    if (!phoneNo || !type) {
      return await ctx.service.returnBody.index(null, '请检查参数！');
    }
    ctx.session = null;
    if (type === 1) {
      await this.addLoginHistory({
        operationType: 2,
        phoneNo,
      });
      return await ctx.service.returnBody.index({});
    }
    if (type === 2) {
      const now = new Date();
      const model = await ctx.model.User.update({
        status: 4,
        updatedTime: now,
      }, {
        where: {
          phoneNo,
        },
      });
      return await ctx.service.returnBody.index(model ? {} : null, '注销失败！');
    }
  }
  async addLoginHistory(params) {
    const ctx = this.ctx;
    const { operationType, phoneNo } = params;
    const model = await ctx.model.User.findOne({
      attributes: [ 'id' ],
      raw: true,
      where: {
        phoneNo,
      },
    });
    if (model) {
      const now = new Date();
      const obj = {
        operationType,
        createId: model.id,
        createdTime: now,
        updatedTime: now,
      };
      await ctx.model.LoginHistory.create(obj);
    }
  }
  async updateUserType(params) {
    const ctx = this.ctx;
    const { id, userType } = params;
    if (!id || !userType) {
      return await ctx.service.returnBody.index(null, '请检查参数！');
    }
    const now = new Date();
    const model = await ctx.model.User.update({
      userType,
      updatedTime: now,
    }, {
      where: {
        id,
      },
    });
    return await ctx.service.returnBody.index(model ? {} : null, '设定管理员失败！');
  }
  async updateUserStatus(params) {
    const ctx = this.ctx;
    const { id, status } = params;
    if (!id || !status) {
      return await ctx.service.returnBody.index(null, '请检查参数！');
    }
    const now = new Date();
    const model = await ctx.model.User.update({
      status,
      updatedTime: now,
    }, {
      where: {
        id,
      },
    });
    return await ctx.service.returnBody.index(model ? {} : null, '更改用户状态失败！');
  }
  async getUserList(params) {
    const ctx = this.ctx;
    const { offset, pageSize, createdTimeStart, createdTimeEnd, status, phoneNo, nickName } = params;
    const body = {
      totalCount: 0,
      list: [],
    };
    const commonSql = `
    from user
    where 1 = 1
    ${createdTimeStart ? `and created_time >= '${createdTimeStart}'` : ''}
    ${createdTimeEnd ? `and created_time < '${createdTimeEnd}'` : ''}
    ${status > 0 ? `and status = ${status}` : ''}
    ${phoneNo ? `and phone_no = ${phoneNo}` : ''}
    ${nickName ? `and nick_name like '%${nickName}%'` : ''}`;
    const totalSql = `
      SELECT count(*) AS total
      ${commonSql}
    `;
    const totalModel = await ctx.model.query(totalSql, { type: 'SELECT' });
    body.totalCount = totalModel && totalModel[0].total;
    if (body.totalCount === 0) {
      return await ctx.service.returnBody.index(body, '获取用户列表失败！');
    }
    const Sql = `select
    id,
    nick_name as nickName,
    phone_no as phoneNo,
    status,
    user_type as userType,
    DATE_FORMAT( created_time,'%Y-%m-%d %H:%i:%s') as createdTime,
    DATE_FORMAT( updated_time,'%Y-%m-%d %H:%i:%s') as updatedTime
    ${commonSql}
    order by created_time desc
    ${pageSize ? `limit ${offset}, ${pageSize}` : ''}`;
    const Model = await ctx.model.query(Sql, { type: 'SELECT' });
    if (Model) {
      body.list = Model;
    }
    return await ctx.service.returnBody.index(body, '获取用户列表失败！');
    // const criteria = ctx.service.list.whereHandleFn(params);
    // const model = await ctx.model.User.findAndCountAll({
    //   attributes: { exclude: [ 'password' ] },
    //   ...criteria,
    // });
    // return await ctx.service.returnBody.index(model, '获取用户列表失败！');
  }
  async getLoginHistory(params) {
    const ctx = this.ctx;
    const { offset, pageSize, createdTimeStart, createdTimeEnd, operationType, phoneNo, nickName } = params;
    const body = {
      totalCount: 0,
      list: [],
    };
    const commonSql = `
    from login_history lh
    left join user on user.id = lh.create_id
    where 1 = 1
    ${createdTimeStart ? `and lh.created_time >= '${createdTimeStart}'` : ''}
    ${createdTimeEnd ? `and lh.created_time < '${createdTimeEnd}'` : ''}
    ${operationType > 0 ? `and lh.operation_type = ${operationType}` : ''}
    ${phoneNo ? `and user.phone_no = ${phoneNo}` : ''}
    ${nickName ? `and user.nick_name like '%${nickName}%'` : ''}`;
    const totalSql = `
      SELECT count(*) AS total
      ${commonSql}
    `;
    const totalModel = await ctx.model.query(totalSql, { type: 'SELECT' });
    body.totalCount = totalModel && totalModel[0].total;
    if (body.totalCount === 0) {
      return await ctx.service.returnBody.index(body, '获取用户记录列表失败！');
    }
    const Sql = `select
    user.nick_name as nickName,
    user.phone_no as phoneNo,
    DATE_FORMAT( lh.created_time,'%Y-%m-%d %H:%i:%s') as createdTime,
    lh.operation_type as operationType
    ${commonSql}
    order by lh.created_time desc
    ${pageSize ? `limit ${offset}, ${pageSize}` : ''}`;
    const Model = await ctx.model.query(Sql, { type: 'SELECT' });
    if (Model) {
      body.list = Model;
    }
    return await ctx.service.returnBody.index(body, '获取用户记录列表失败！');
  }
}

module.exports = userInfoService;
